#include"QueryResult.h"
#include"Util.h"
#include"Sentence.h"

vector<string> QueryResult::processWord(const string &word){
    vector<string> wordList;
    auto hd = word.begin(),re = word.begin();
    while(re != word.end()){
        if(*re == '\n'){    //简便起见,句内换行按空格处理
            cout << " ";
            hd++;
            re++;
        }
        else if(!isalpha(*re)){
            hd++;
            re++;
        }      
        else{
            while(isalpha(*re))
                re++;
            if(!(*(hd - 1) == '~'))     
                wordList.push_back(tolowerStr(string(hd,re)));
            hd = re;
        }
    }
    return wordList;
}

void QueryResult::highlightAt(string &cont, const string &word){
    auto hd = cont.begin(), re = cont.begin();
    while(re != cont.end()){
        if(!isalpha(*re)){
            hd++;
            re++;
        }
        else{
            while(isalpha(*re))
                re++;
            string scanWord = string(hd,re);
            if(tolowerStr(word) == tolowerStr(scanWord)){
                cont.replace(hd,re,highlight(scanWord));
                break;
            }
            hd = re;
        }
    }
}

void QueryResult::print(){
    vector<string> wordList = processWord(word_);
    if(DEBUG) {
        cout << "wordList:";
        for(string str : wordList){
            cout << str << " ";
        }
        cout << "\n";
    }
    for(int idx : *idxs_){
        Sentence st = (*file_)[idx];  
        string content = st.contents;
        auto hd = content.begin(), re = content.begin();
        for(string wd : wordList){
            highlightAt(content,wd);
        }
        printf("(line %4d) ",st.line);
        cout << content;
        cout << "\n";
    }
    cout << "query for " << word_ << " have " << idxs_->size() << " records" << endl;
    
}